<template>
  <div>
    <div v-show="imgs.length && !isAddingAnnotation">
      <div
        class="answer-img-container"
        :class="{ grabbing: isDragging }"
        @pointerdown="onPointerDown"
        @pointermove="onPointerMove"
        @pointerup="onPointerUp"
      >
        <div class="view-wrapper" :style="styleStr">
          <ScoreClick
            :totalScore="props.totalScore"
            :location-list="props.locationList"
            :current-index="imgIndex"
            :total-num="imgs.length"
          >
            <div class="img-container">
              <img
                :draggable="false"
                class="paper-img"
                :src="actImgUrl[imgIndex]"
                :style="{
                  transform: `${isRotated ? 'rotate(180deg)' : 'rotate(0)'}`
                }"
              />
            </div>
          </ScoreClick>
        </div>
      </div>
      <div class="flex-end tool-box">
        <div class="flex">
          <el-button
            type="primary"
            text
            class="annotation-btn"
            @click="onToggleMark"
          >
            <AnnotationBtn class="img" />
            批注
          </el-button>
          <div class="control-btn flex">
            <div
              class="btn btn-left hover"
              @click="onScroll('left')"
              :class="imgIndex === 0 && 'btn-disable'"
            ></div>
            {{ imgIndex + 1 }} / {{ imgs.length }}
            <div
              class="btn btn-right hover"
              :class="
                (imgs.length === 1 || imgIndex === imgs.length - 1) &&
                'btn-disable'
              "
              @click="onScroll('right')"
            ></div>
          </div>
        </div>
      </div>
    </div>
    <div v-if="imgs.length && isAddingAnnotation">
      <AnnotationBox
        :act-url="actImgUrl[imgIndex]"
        :img-url="imgs[imgIndex]"
        :old-url="oldUrl"
        class="answer-img-box"
      />
      <AnnotationControl :is-has-his-url="!!oldUrl" />
    </div>
  </div>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { annotateMitt } from '@/utils/tools/bus'
import AnnotationBtn from '@/assets/images/assignment/annotation.svg'
import AnnotationBox from '@/components/annotation/AnnotationBox.vue'
import AnnotationControl from '@/components/annotation/AnnotationControl.vue'
import ScoreClick from '@/components/score-board/ScoreClick.vue'

const props = defineProps({
  historyImg: {
    // 历史批注的图片
    type: String,
    required: true
  }, // 已批注的图片
  imgUrl: { type: String, required: true }, // 原图片
  scaleRatio: { type: Number, default: 1 },
  isRotated: { type: Boolean, default: false },
  totalScore: {
    type: Number,
    default: 0
  },
  locationList: {
    type: Array,
    default: () => []
  }
})
const emit = defineEmits(['updateAnnotationImgUrl'])
const imgs = ref([]) // 原图片
const historyUrl = ref([]) // 批注图片
const actImgUrl = ref([]) // 操作图片
const oldUrl = computed(() => historyUrl.value[imgIndex.value] || '')
const imgIndex = defineModel('imgIndex', {
  default: 0
})

const onScroll = type => {
  if (type === 'left') {
    imgIndex.value = imgIndex.value === 0 ? 0 : imgIndex.value - 1
    return
  }
  imgIndex.value =
    imgIndex.value === imgs.value.length - 1
      ? imgIndex.value
      : imgIndex.value + 1
}

// ==== start 批注相关
const isAddingAnnotation = defineModel('isAddingAnnotation') // 是否开启批注
const onToggleMark = () => {
  isAddingAnnotation.value = !isAddingAnnotation.value
}
const annotateMittListener = () => {
  annotateMitt.on('annotationControl', param => {
    let { model } = param
    switch (model) {
      case 'cancel':
        isAddingAnnotation.value = false
        break
      case 'save-img-url':
        isAddingAnnotation.value = false
        actImgUrl.value[imgIndex.value] = param.url
        emit('updateAnnotationImgUrl', actImgUrl.value)
        break
    }
  })
}

// ==== end 批注相关

// === start 图片拖拽相关
const isDragging = ref(false)
const translateX = ref(0)
const translateY = ref(0)
const resetXY = () => {
  translateX.value = 0
  translateY.value = 0
}
const onPointerDown = () => {
  isDragging.value = true
}

const onPointerUp = () => {
  isDragging.value = false
}

const onPointerMove = e => {
  if (!isDragging.value) {
    return
  }
  const { movementY, movementX } = e
  // 给点击事件一个手滑的缓冲区
  if (Math.abs(movementY) < 3 && Math.abs(movementX) < 3) {
    return
  }

  if (props.scaleRatio > 1) {
    translateY.value += movementY
    translateX.value += movementX
  }
}
const styleStr = computed(() => {
  return `transform:  translate(${translateX.value}px,${translateY.value}px) scale(${props.scaleRatio})`
})
// === end 图片拖拽相关

defineExpose({
  resetXY
})
watch(
  () => props.imgUrl,
  () => {
    isAddingAnnotation.value = false
    imgs.value = JSON.parse(props.imgUrl)
    historyUrl.value = JSON.parse(props.historyImg || '[]')
    imgIndex.value = imgs.value.length ? 0 : null
    actImgUrl.value = historyUrl.value.length
      ? [...historyUrl.value]
      : [...imgs.value]
  },
  {
    immediate: true
  }
)
const initData = () => {
  annotateMittListener()
}
initData()
</script>

<style scoped lang="less">
@baseURL: '@/assets/images/single-correct';
.answer-img-container {
  width: 100%;
  position: relative;
  overflow: hidden;
  background-color: #d9d9d9;
  .view-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    transform-origin: top;
    max-height: calc(100vh - 220px);
    overflow: scroll;
    scrollbar-width: none;
    .img-container {
      width: 100%;
      height: 100%;
      position: relative;
      user-select: none;
      .paper-img {
        display: block;
        border: 1px solid #d9d9d9;
        box-sizing: border-box;
        width: 100%;
        background-color: rgba(232, 232, 232, 0.5);
        background-image: url('@{baseURL}/loading.svg');
        background-repeat: no-repeat;
        background-position: center;
        transition: all 200ms;
      }
    }
  }
}
.tool-box {
  margin-top: 10px;
  .annotation-btn {
    gap: 20px;
    .img {
      margin-top: -2px;
      margin-right: 4px;
    }
  }
  .control-btn {
    gap: 30px;
    .btn {
      width: 30px;
      height: 30px;
      margin-bottom: -4px;
    }
    .btn-disable:hover {
      cursor: not-allowed;
    }
    .btn-left {
      background-image: url('@{baseURL}/left-btn.svg');
      background-repeat: no-repeat;
      background-size: contain;
    }
    .btn-right {
      background-image: url('@{baseURL}/right-btn.svg');
      background-size: contain;
      background-repeat: no-repeat;
    }
  }
}
.grabbing {
  cursor: grabbing;

  .click-score-mode {
    cursor: inherit;
  }
}
.answer-img-box {
  width: calc(100vw - 280px - 446px);
}
</style>
